package com.boomsecret.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by wangjinliang on 2018/8/6.
 */
public final class DateUtils {
    private DateUtils() {}

    private static Date getOffsetWeekTime(Date date, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - offset);
        return calendar.getTime();
    }

    private static Date getOffsetMonthTime(Date date, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - offset);
        return calendar.getTime();
    }

    private static Date getOffsetYearTime(Date date, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - offset);
        return calendar.getTime();
    }

    public static Date getCurrentDayLastSecondTime() {
        return new Date(getCurrentDayZeroTime().getTime() + 24 * 3600 * 1000 -1);
    }

    public static Date getCurrentDayZeroTime() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date();
        System.out.println("当前时间是：" + dateFormat.format(date));

        Date preWeekDate = getOffsetWeekTime(date, 1);
        System.out.println("上周是：" + dateFormat.format(preWeekDate));

        Date preDate = getOffsetMonthTime(date, 1);
        System.out.println("上个月同日是：" + dateFormat.format(preDate));

        Date preYearDate = getOffsetYearTime(date, 1);
        System.out.println("去年今日是：" + dateFormat.format(preYearDate));
    }
}
